package com.kuaiditu.assistant.ui.scan;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.zxing.Result;
import com.google.zxing.client.android.ViewfinderView;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.assistant_api.AssistantApi;
import com.kuaiditu.assistant.api.assistant_api.base.AssistantResponse;
import com.kuaiditu.assistant.api.xz_api.XingZheApi;
import com.kuaiditu.assistant.api.yd_api.YDApi;
import com.kuaiditu.assistant.db.ExpressEntity;
import com.kuaiditu.assistant.db.ExpressManager;
import com.kuaiditu.assistant.db.ExpressStateListener;
import com.kuaiditu.assistant.entity.Operator;
import com.kuaiditu.assistant.entity.OperatorDao;
import com.kuaiditu.assistant.module.retrofit.ProgressSubscriber;
import com.kuaiditu.assistant.util.RegExpUtil;
import com.kuaiditu.assistant.util.ToastUtil;
import com.kuaiditu.assistant.view.topbar.TopBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;


@Route(path = ScanExpressSheetActivity.PATH)
@RuntimePermissions
public class ScanExpressSheetActivity extends BaseScanActivity implements ExpressStateListener {

    AssistantApi mAssistantApi;

    public static final String PATH = "/user/scan_express";

    @Autowired
    int task_id;

    @Autowired
    int express_com_id;


    @BindView(R.id.top_bar)
    TopBar topBar;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.tv_input)
    TextView tvInput;
    @BindView(R.id.rv_scan_express)
    RecyclerView rvScanExpress;

    ScanExpressAdapter mScanExpressAdapter;


    List<String> expresses = new ArrayList<>();


    XingZheApi mXingZheApi;


    YDApi mYDApi;


    @BindView(R.id.preview_view)
    SurfaceView surfaceView;
    @BindView(R.id.viewfinder_view)
    ViewfinderView viewfinderView;


    @Autowired
    int scan_type = 0;

    Operator mOperator;

    AlertDialog dialog;

    private ExpressManager mExpressManager;


    @Override
    public int initContentView() {
        return R.layout.activity_scan_express_sheet;
    }

    @Override
    public void initInjector() {
        mAssistantApi = getApplicationComponent().getApiManager().getAssistantApi();
        ARouter.getInstance().inject(this);
        mXingZheApi = getApplicationComponent().getApiManager().getXingZheApi();
        mYDApi = getApplicationComponent().getApiManager().getYDApi();
        mOperator = getApplicationComponent().getDaoSession().getOperatorDao().queryBuilder().where(OperatorDao.Properties.Task_id.eq(task_id)).unique();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
//        mScaner.setDelegate(this);
        topBar.bind(this, true);

        if (scan_type == 0) {
            topBar.setTitle("派件扫描");
        } else {
            topBar.setTitle("签收扫描");
        }


        mExpressManager = new ExpressManager(task_id, express_com_id, getApplicationComponent().getApiManager(), getApplicationComponent().getDaoSession(), mOperator);
        mExpressManager.setExpressStateListener(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        rvScanExpress.setLayoutManager(linearLayoutManager);
        rvScanExpress.setAdapter(mScanExpressAdapter = new ScanExpressAdapter(expresses));
        rvScanExpress.addItemDecoration(new DividerItemDecoration(rvScanExpress.getContext(), linearLayoutManager.getOrientation()));
        ScanExpressSheetActivityPermissionsDispatcher.showCameraWithCheck(this);
    }


    @Override
    protected boolean setTranslucent() {
        return true;
    }

    @Override
    protected boolean setStatusBar() {
        return false;
    }

    public void onScanQRCodeSuccess(String result) {
//        vibrate();
        if (!expresses.contains(result)) {
            if (scan_type == 0) {
                addOrder(result);
            } else {
                signOrder(result);
            }
        } else {
            ToastUtil.showToast(result + "\n已存在");
            reScan();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public SurfaceView getSurfaceView() {
        return (surfaceView == null) ? (SurfaceView) findViewById(R.id.preview_view) : surfaceView;
    }

    @Override
    public void dealDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        playBeepSoundAndVibrate();
        String code = rawResult.getText();

        if (RegExpUtil.isNum(code)) {
            if (code.length() > 6) {
                onScanQRCodeSuccess(code);
            } else {
                ToastUtil.showToast("单号有误：\n" + code);
                reScan();
            }

        } else {
            ToastUtil.showToast("单号有误：\n" + code);
            reScan();
        }

    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public ViewfinderView getViewfinderHolder() {
        return (viewfinderView == null) ? (ViewfinderView) findViewById(R.id.viewfinder_view) : viewfinderView;
    }


    private void addOrder(final String express) {
        mExpressManager.addAcceptExpress(express)
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onNext(AssistantResponse assistantResponse) {
                        expresses.add(0, express);
                        tvHint.setText(String.format("本次共扫描%s单", expresses.size()));
                        mScanExpressAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
                        reScan();
                    }
                });

    }


    private void signOrder(final String express) {
        mExpressManager.addSignExpress(express)
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onNext(AssistantResponse assistantResponse) {
                        expresses.add(0, express);
                        tvHint.setText(String.format("本次共扫描%s单", expresses.size()));
                        mScanExpressAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
                        reScan();
                    }
                });

//
//        mAssistantApi.signOrder(String.valueOf(task_id), express, mOperator.getName())
//                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
//                    @Override
//                    public void onStart() {
//
//                    }
//
//                    @Override
//                    public void onNext(AssistantResponse assistantResponse) {
//                        expresses.add(express);
//                        tvHint.setText(String.format("本次共扫描%s单", expresses.size()));
//                        mScanExpressAdapter.notifyDataSetChanged();
//                    }
//
//                    @Override
//                    public void onFinish() {
//
//                    }
//                });

//
//        mYDApi.addSignExpress(express, mOperator.getYd_id())
//                .subscribe(new ProgressSubscriber<YDBaseResponse>(mContext) {
//                    @Override
//                    public void onStart() {
//
//                    }
//
//                    @Override
//                    public void onNext(YDBaseResponse response) {
//                        if (response.getDeEntity().getJSONObject("dta").getString("st").equals("ok")) {
//                            mAssistantApi.signOrder(String.valueOf(task_id), express, mOperator.getName())
//                                    .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
//                                        @Override
//                                        public void onStart() {
//
//                                        }
//
//                                        @Override
//                                        public void onNext(AssistantResponse assistantResponse) {
//                                            expresses.add(express);
//                                            tvHint.setText(String.format("本次共扫描%s单", expresses.size()));
//                                            mScanExpressAdapter.notifyDataSetChanged();
//                                        }
//
//                                        @Override
//                                        public void onFinish() {
//
//                                        }
//                                    });
//
//                        } else {
//                            ToastUtil.showToast(response.getDeEntity().getJSONObject("dta").getString("ermsg"));
//                        }
//                    }
//
//                    @Override
//                    public void onFinish() {
//
//                    }
//                });

    }


    @Override
    public void onBackPressed() {
        if (expresses.isEmpty()) {
            super.onBackPressed();
        } else {
            setResult(Activity.RESULT_OK);
            finish();
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        } else if (item.getItemId() == R.id.menu_input) {
            showInput();
        }
        return super.onOptionsItemSelected(item);
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {

    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("扫描功能需要条用摄像头权限")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("禁止", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();

                    }
                }).show();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "拍照权限被拒绝，扫描功能无法正常使用", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(this, "拍照权限被拒绝，扫描功能无法正常使用", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        ScanExpressSheetActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);

    }

    @Override
    public void onExpressAdd(ExpressEntity expressEntity) {
//        expresses.add(0, expressEntity.getExpress_num());
//        mScanExpressAdapter.notifyDataSetChanged();
    }

    @Override
    public void onExpressChange(ExpressEntity expressEntity) {

    }


    private void showInput() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("手动输入面单");
        builder.setCancelable(false);
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_input_code_layout, null);
        final EditText edit_code = (EditText) view.findViewById(R.id.edit_express);
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.btn_enter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(edit_code.getText().toString())) {
                    onScanQRCodeSuccess(edit_code.getText().toString());
                }
                dialog.dismiss();
            }
        });

        builder.setView(view);
        dialog = builder.create();
        dialog.show();
    }


    @OnClick(R.id.tv_input)
    public void input() {
        showInput();
    }


}
